# This file is part of trytond-fyireporting module for Tryton. 
# The COPYRIGHT file at the top level of this repository contains 
# the full copyright notices and license terms.

import logging
from trytond.pool import Pool
from trytond.report import Report
from trytond.cache import Cache
import tempfile
import os
#from rdl.fyireporting import RdlReport
from trytond.transaction import Transaction
import subprocess

class FyireportingReport(Report):
    _get_report_file_cache = Cache('fyireporting.report_file')

    @classmethod
    def get_report_file(cls, report, path=None):
        logger = logging.getLogger('RDL Report')

        cache_path = cls._get_report_file_cache.get(report.name)
        if cache_path is not None:
            return cache_path

        if not path:
            path = tempfile.mkdtemp(prefix='trytond-rdl-')

        report_content = str(report.report_content)

        if not report_content:
            raise Exception('Error', 'Missing report file!')

        fname = os.path.split(report.report)[-1]
        logger.info("fname: " + fname)
        basename = fname.split('.')[0]
        logger.info("basename: " + basename)
        rdl_path = os.path.join(path, fname)
        logger.info("rdl_path: " + rdl_path)

        f = open(rdl_path, 'w')
        try:
            f.write(report_content)
        finally:
            f.close()

        cls._get_report_file_cache.set(report.name, rdl_path)
        return rdl_path


    @classmethod
    def execute(cls, ids, data):
        pool = Pool()
        ActionReport = pool.get('ir.action.report')

        logger = logging.getLogger('RDL Report')
        logger.info("Running rdl report")

        report_actions = ActionReport.search([
                ('report_name', '=', cls.__name__)
                ])
        if not report_actions:
            raise Exception('Error', 'Report (%s) not found!' % cls.__name__)

        report_action = report_actions[0]
        report_path = cls.get_report_file(report_action)
        output_format = data.get('output_type', None)
        if not output_format:
            output_format = report_action.extension

        Config = pool.get('fyireporting.configuration')
        config = Config(1)
        
        rdlcmd = config.path_rdlcmd
        mono = config.path_mono
  
        rdl = RdlReport(report_path, rdlcmd, mono)

        rdl.set_parameter("conn_string", config.conn_string)
        company_info = cls.get_company_data()
        rdl.set_parameter("company_id", company_info["company_id"])
        rdl.set_parameter("company_name", company_info["company_name"])

        for key in data:
            if key == "output_type":
                continue
            rdl.set_parameter(key, str(data[key]))
        file_data = rdl.get_result_file(output_format)

        return (output_format, buffer(file_data), report_action.direct_print,
            report_action.name)

    @classmethod
    def get_company_data(cls):
        pool = Pool()
        res = {"company_id":"-1", "company_name": "None"}

        company_id = Transaction().context.get('company')
        if company_id:
            Company = pool.get('company.company')
            company = Company(company_id)
            res["company_id"] = str(company.id)
            res["company_name"] = str(company.party.name)

        return res


class RdlReport :

    __report_path=""
    __parameters = {}

    def __init__(self, report_path, path_to_rdlcmd, path_to_mono):
        self.__report_path = report_path
        self.__path_to_rdlcmd = path_to_rdlcmd
        self.__path_to_mono = path_to_mono 


    def set_parameter(self, name, value):
        '''
         Set a parameters values
         name - string - the report parameter name
         value - string - the value of the parameter
        '''
        self.__parameters.update({name:value})


    def get_result_file(self, type=None):
        '''
         Export report to a file on the server
         type - string - Export type "pdf", "csv", "xslx", "xml", "rtf", "tif", "html".  If type does not match it will default to PDF.
         export_type - string - path on server to export file
        '''

        type = self.get_type(type)
        cmd = []

        # mono is required to run rdlcmd on linux
        if self.__path_to_mono or self.__path_to_mono != "":
            cmd.append(self.__path_to_mono)
        cmd.append(self.__path_to_rdlcmd)

        rdl_file = self.__report_path
        rdl_folder = os.path.dirname(self.__report_path)

        #add path to rdl file
        rdl_path = "/f" + rdl_file

        # Add all parameters to report
        count=0
        print self.__parameters
        for key in self.__parameters:
            if (count == 0):
                rdl_path = rdl_path + '?' + key + '=' + self.__parameters[key]
            else:
                rdl_path = rdl_path + '&' + key + '=' + self.__parameters[key]
            count = count + 1

        cmd.append(rdl_path)

        # set the export type
        cmd.append('/t' + type)

        #set the folder that the file will be exported
        cmd.append('/o' + rdl_folder)

        subprocess.call(cmd)

        basename = os.path.basename(self.__report_path)
        basename = basename.split('.')[0]
        temp_pdf = rdl_folder + os.sep + basename + "." + type

        f = open(temp_pdf, 'r+')
        data = f.read()
        f.close()
        os.remove(temp_pdf)

        return data


    def get_type(self, type):
        rtype = type
        if type not in ("pdf", "csv", "xslx", "xml", "rtf", "tif", "html"):
            rtype = "pdf"
        return rtype


